﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using ProtoBuf.Meta;

namespace NewsMine.Utilities
{
    public class ObjectByteArrayConverter
    {
        public static byte[] ObjectToByteArray(Object obj)
        {
            MemoryStream fs = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, obj);
                return fs.ToArray();
            }
            catch (SerializationException e)
            {
                throw new ApplicationException("Error while serializing the object to bytes, make sure you mark the object class as serializable", e);
            }
            finally
            {
                fs.Close();
            }
        }


        public static byte[] ObjectToByteArrayProtoBuff<T>(Object obj)
        {
            
            MemoryStream fs = new MemoryStream();

            try
            {
                ProtoBuf.Serializer.Serialize(fs, obj);
                return fs.ToArray();
            }
            catch (SerializationException e)
            {
                throw new ApplicationException("Error while protobuff serializing the object to bytes, make sure you mark the object class as serializable", e);
            }
            finally
            {
                fs.Close();
            }
        }


        public static object ByteArrayToObjectProtoBuff<T>(Byte[] Buffer)
        {
            MemoryStream stream = new MemoryStream(Buffer);
            try
            {
                object obj = ProtoBuf.Serializer.Deserialize<T>(stream);

                return obj;
            }
            catch
            {
                return null;
            }
        }


        public static object ByteArrayToObject(Byte[] Buffer)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(Buffer);
            try
            {
                return formatter.Deserialize(stream);
            }
            catch
            {
                return null;
            }
        }
    }
}
